package com.kly.user.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Maps;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.UserAppsflyerFromAppEntity;
import com.kly.user.db.entity.UserAppsflyerReportDetailEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.dto.TrafficSourceDto;
import com.kly.user.dto.vo.TrafficSourceReq;
import com.kly.user.enums.AppCodeEnum;
import com.kly.user.enums.TrafficSourceEnum;
import com.kly.user.service.UserTrafficSourceService;
import com.kly.user.service.WhiteListService;
import com.kly.user.service.traffic.TrafficFacadeService;
import com.kly.user.serviceImpl.dto.TrafficSourceEnableSwitch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 流量来源分类
 * @author linqu
 */
@Slf4j
@Service("userTrafficSourceService")
public class UserTrafficSourceServiceImpl implements UserTrafficSourceService {

    @NacosValue(value = "${traffic.source.enable.switch}", autoRefreshed = true)
    private String trafficSourceEnableSwitch;

//    @Autowired
//    private Map<String, TrafficFacadeService> trafficFacadeService;


    public static Map<String, TrafficFacadeService> trafficFacadeService = Maps.newHashMap();
    /**
     * 开关，根据appCode返回开关设置：0-关闭 1-开启 2-保持
     */
    @Override
    public Response<Integer> getTrafficControlEnableSwitch(String appCode) {
        if (StringUtils.isEmpty(appCode)) {
            return Response.error("appCode should not be empty");
        }

        final List<TrafficSourceEnableSwitch> trafficSourceList = JSONObject.parseArray(trafficSourceEnableSwitch, TrafficSourceEnableSwitch.class);
        final Integer enableSwitch = trafficSourceList.parallelStream().filter(o -> o.getAppCode().equals(appCode)).findFirst()
                .map(TrafficSourceEnableSwitch::getTrafficSourceEnableSwitch).orElse(2);
        return Response.ok(enableSwitch);

    }

    /**
     * 返回自然流量或非自然流量
     */
    @Override
    public Response<TrafficSourceDto> getTrafficSource(TrafficSourceReq req) {
        log.info("===获取渠道参数：req:{}", JSONObject.toJSONString(req));
        final TrafficFacadeService trafficFacadeService = UserTrafficSourceServiceImpl.trafficFacadeService.get(req.getAppCode());
        return trafficFacadeService.getTrafficSource(req, req.getAppCode());
    }
}
